<template>
  <div>
    <van-popup class="sms" v-model="showPopup" :overlay="true">
      <van-cell-group v-for="(item, index) in providerData" :key="item.channel_priority">
         <van-field
          v-model.trim="item.code"
          ref="code"
          center
          :label="(item.provider_partner_name).substring(0,2)"
          placeholder="请输入短信验证码"
          error-message=""
        >
          <van-button slot="button" :disabled="item.disabled" @click="send(index)" size="small">
            <span v-show="item.show">{{item.btnTxt}}</span>
            <span v-show="!item.show" class="count">{{item.count}} s</span>
          </van-button>
        </van-field>
        <p class="error">{{item.errorMsg}}</p>
      </van-cell-group>
      <van-button size="large" @click="submitCode">大号按钮</van-button>
    </van-popup>
  </div>
</template>

<script type="text/javascript">
export default {
  data () {
    return {
      code:'',
      timer: null,
      sms: '',
      phone: '',
      error: false,
      list: '',
      showPopup: true
    }
  },
  props: {
    providerData: Array
  },
  mounted () {
    this.getCode (0)
  },
  methods:{
    submitCode (index) {
      let obj = []
      for (let i = 0; i < this.providerData.length; i++) {
        if (this.$refs.code[i].value !== undefined) {
          obj.push({
            provider_partner_id: this.providerData[i].provider_partner_id,
            code: this.providerData[i].code
          })
        }
      }
      console.log(obj)
      this.$emit('submitCode', obj)
    },
    send (index) {
      this.getCode(index)
      // this.submitCode(index)
    },
    getCode (index) {
      this.providerData[index].count = 60;
      this.providerData[index].show = false;
      this.timer = setInterval(() => {
        if (this.providerData[index].count > 0 && this.providerData[index].count <= 60) {
          this.providerData[index].count--;
        } else {
          this.providerData[index].show = true;
          this.providerData[index].btnTxt = '重新发送'
          clearInterval(this.timer);
          this.timer = null;
        }

        for (let i = 0; i < this.providerData.length; i++) {
          if (this.providerData[index].show) {
            this.providerData[i].disabled = false;
          } else {
            this.providerData[i].disabled = true; 
          }   
        }
      }, 1000)
    }   
  }
}
</script>

<style type="text/css">
[class*=van-hairline]::after {
  border: none;
}
.sms {
  width: 320px;
}
.error {
  font-size: 12px;
  color: red;
}
</style>
